import axios, {AxiosInstance} from 'axios';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Session} from '/@/utils/storage';
import qs from 'qs';
import {buildParamsSignStr, generateRandomString, getObjectFromFormData} from "/@/utils/format";

// 配置新建一个 axios 实例
const service: AxiosInstance = axios.create({
    // baseURL: import.meta.env.VITE_API_URL, // product
    baseURL: import.meta.env.MODE == 'production' ? import.meta.env.VITE_API_URL : import.meta.env.VITE_PROXY_TAG, // dev
    timeout: 50000,
    // headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
    paramsSerializer: {
        serialize(params) {
            return qs.stringify(params, {allowDots: true});
        },
    },
});

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        // 在发送请求之前做些什么 token
        if (Session.get('token')) {
            config.headers!['JToken'] = `${Session.get('token')}`;
        }
        config.headers!['X-App-Id'] = import.meta.env.VITE_APP_ID;
        let _params = {};
        const extParams = {
            '_time': new Date().getTime(),
            'sceneStr': generateRandomString(8)
        };
        if (config.method == 'get') {
            _params = {...extParams, ...config.params}
            const _signStrParams = {
                'sign': buildParamsSignStr(_params)
            };
            config.params = {..._params, ..._signStrParams}
        } else {
            if (config.data instanceof FormData) {
                config.data.append('_time', new Date().getTime().toString())
                config.data.append('sign', buildParamsSignStr(getObjectFromFormData(config.data)))
            } else {
                _params = {...extParams, ...config.data}
                const _signStrParams = {
                    'sign': buildParamsSignStr(_params)
                };
                config.data = {..._params, ..._signStrParams}
            }
        }

        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        const res = response.data;
        const code = response.data.code
        if (code === 401) {
            ElMessageBox.alert('登录状态已过期，请重新登录', '提示', {confirmButtonText: '确定'})
                .then(() => {
                    Session.clear(); // 清除浏览器全部临时缓存
                    window.location.href = '/'; // 去登录页
                })
                .catch(() => {
                });
        } else if (code !== 200) {
            ElMessage.error(res.msg)
            return Promise.reject(new Error(res.msg))
        } else {
            return res
        }
    },
    (error) => {
        // 对响应错误做点什么
        if (error.message.indexOf('timeout') != -1) {
            ElMessage.error('网络超时');
        } else if (error.message == 'Network Error') {
            ElMessage.error('网络连接错误');
        } else {
            if (error.response.data) ElMessage.error(error.response.statusText);
            else ElMessage.error('接口路径找不到');
        }
        return Promise.reject(error);
    }
);

// 导出 axios 实例
export default service;
